<template>
  <div class="search-view">
    <div class="search-btn">
      <el-button @click="handleSeach">拉框搜索</el-button>
    </div>
    <div class="search-table" v-show="tableData.length">
      <el-table :data="tableData" @row-click="handleRowClick">
        <el-table-column prop="event_num" label="事件编号" />
        <el-table-column prop="level" label="事故级别" />
        <el-table-column prop="area" label="事故区域" />
        <el-table-column prop="name" label="事故类型" />
        <el-table-column prop="car_num" label="车牌号码"> </el-table-column>
        <el-table-column prop="phone" label="联系电话" />
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, inject, onMounted } from 'vue'
import { DrawRect } from '@antv/l7-draw'
import { getWuhanEvents } from '@/api'
import { PointLayer } from '@antv/l7'
import { pointsWithinPolygon } from '@turf/turf'
const { map, scene } = inject('mapScene')
const eventData = ref([]) //eventData就是所有的点数据
const tableData = ref([]) //tableData就是拉框搜索后的数据
let pointLayer
let draw
onMounted(async () => {
  map.flyTo({
    center: [114.406325, 30.465113],
    zoom: 15,
    pitch: 45,
  })
  //请求所有的交通事故数据
  const { data } = await getWuhanEvents()
  eventData.value = data
})
function handleSeach() {
  //添加交互式画笔
  if (draw) {
    draw.clear()
    draw.destroy()
    draw = null
  }
  draw = new DrawRect(scene, {})
  draw.enable()
  if (pointLayer) {
    scene.removeLayer(pointLayer)
    pointLayer = null
  }
  draw.on('add', (e) => {
    pointLayer = new PointLayer()
    //实现拉框查询 得到查询到的数据(tableData)
    let result = pointsWithinPolygon(eventData.value, e)
    pointLayer.source(result).shape('circle').size(30).color('pink').animate(true).active(true)
    scene.addLayer(pointLayer)
    //result是geojson的数据格式 转成一个普通的对象
    tableData.value = result.features.map((item) => {
      return { ...item.properties, center: item.geometry.coordinates }
    })
  })
}
function handleRowClick(row) {
  if (draw) {
    draw.destroy()
    draw = null
  }
  let center = row.center
  map.flyTo({
    center: center,
    zoom: 12,
    pitch: 0,
  })
}
</script>

<style lang="scss" scoped>
.search-view {
  .search-btn {
    position: fixed;
    top: 200px;
    right: 60px;
    z-index: 999;
  }
  .search-table {
    position: fixed;
    width: 60%;
    bottom: 100px;
    left: 20%;
    z-index: 999;
  }
  .el-table {
    max-height: 300px;
    overflow-y: auto;
  }
  :deep(.el-table__cell) {
    background-color: #ccc;
  }
}
</style>
